#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include "comm.chh"


//using namespace std;

bool MakeFilo()
{
    int n = mkfifo(FILENAME, 0666);
    if(n < 0)
    {
        std::cerr << "errno: " << errno << "errstring: " << strerror(errno) << std::endl;
        return false;
    }
    return true;
    std::cout << "create fifo succes" << std::endl;
    sleep(2);
}

int main()
{
Start:
    int rfd = open(FILENAME, O_RDONLY);
    if(rfd < 0)
    {
        std::cerr << "errno: " << errno << "errstring: " << strerror(errno) << std::endl;
        if(MakeFilo())
            goto Start;  
        else return 1;
    }
    std::cout << "open fifo successs...read" << std::endl;
    sleep(2);

    char buffer[1024];
    while(true)
    {
        ssize_t s = read(rfd, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << "Client say: " << buffer << std::endl;
        }
        else if(s == 0)
        {
            std::cout << "client quit, server qiut too" << std::endl;
            break;
        }
    }

    sleep(2);

    close(rfd);
    std::cout << "close fifo success" << std::endl;
    return 0;
}